package org.example.securitydemo.config;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 会话并发处理
 * 后登陆的账号会使先登陆的账号失效
 */
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {

        Map<String,Object> result = new HashMap<>();
        result.put("code", -1); // 失败
        result.put("message", "该账号已从其他设备登陆");

        // 将结果对象转换成json字符串
        String json = JSON.toJSONString(result);

        HttpServletResponse response = event.getResponse();
        // 返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
    }
}
